#include"../include/lib_headers.h"
char* delete_dir(char *path) {
	int i = 0, j = 0, k = 0, match = 0, t = 0;
	char s[SIZE] = "", *split_char, *p[SIZE], copy[SIZE] = "", *str;
	node *temp, *prev, *deleted;

	/* Insufficient Arguments */
	if(strlen(path) == 0 ){
		sprintf(output_message, "%s %s", "deletedir_FAILURE",
				ERR_VFS_DELETEDIR_00);
		return output_message;
	}

	/* VFS not mounted */
	if (h == NULL || l1 == NULL ) {
		sprintf(output_message, "%s %s", "deletedir_FAILURE",
				ERR_VFS_DELETEDIR_04);
		return output_message;
	}
	
	
	/* Can't find Specified Directory */
	if (find_node(l1->next, path) == NULL || path[0] != '/' ) {
		sprintf(output_message, "%s %s", "deletedir_FAILURE",
				ERR_VFS_DELETEDIR_01);
		return output_message;
	}

	/* Directory is not empty */
	if (find_node(l1->next, path)->child != NULL) {
		sprintf(output_message, "%s %s", "deletedir_FAILURE",
				ERR_VFS_DELETEDIR_02);
		return output_message;
	}

	/* This function can only delete a directory */
	if (strcmp(find_node(l1->next, path)->fd_pointer->fileType, "dir") != 0) {
		sprintf(output_message, "%s %s", "deletedir_FAILURE",
				ERR_VFS_DELETEDIR_01);
		return output_message;
	}

	split_char = "/";
	str = add_slash(path);
	strcpy(s, str);
	i = splits_directory(s, p, split_char);
	temp = l1->next;
	prev = temp;
	match = 0;
	j = 0;
	while (j < i) {
		while (temp != NULL) {
			if (strcmp(temp->fd_pointer->fileName, p[j]) == 0) {
				match = 1;
				j++;
				if (j == i) {
					break;
				}
				prev = temp;
				temp = temp->child;
			}
			if (match == 0) {
				prev = temp;
				temp = temp->sibling;
			} else if (match == 1) {
				match = 0;
				continue;
			}
		}
	}

	if (prev->child == temp) {
		prev->child = temp->sibling;
		freelist[temp->fd_pointer->blockno] = 0;
		h->usedFds--;
		del(temp->fd_pointer->fullPath);
		htable_delete(hashtable, *(temp->fd_pointer));
		free(temp);
	}

	else if (prev->sibling == temp) {
		prev->sibling = prev->sibling->sibling;
		freelist[temp->fd_pointer->blockno] = 0;
		h->usedFds--;
		del(temp->fd_pointer->fullPath);		
		htable_delete(hashtable, *(temp->fd_pointer));
		free(temp);
	}

	else if (l1->next == prev) {
		l1->next = prev->sibling;
		freelist[prev->fd_pointer->blockno] = 0;
		h->usedFds--;
		del(prev->fd_pointer->fullPath);		
		htable_delete(hashtable, *(prev->fd_pointer));
		free(prev);
	}

	sprintf(output_message, "%s", "deletedir_SUCCESS");
	return output_message;
}
